package erz.printing.police.notch;

import android.content.Context;
import android.graphics.Rect;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.view.Window;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

class MiNotchScreenSupport implements INotchScreenSupport {
    //绘制到刘海区域
    private final int FLAG_NOTCH_IMMERSIVE = 0x00000100;
    //竖屏绘制到刘海区域
    private final int FLAG_NOTCH_PORTRAIT = 0x00000200;
    //横屏绘制刘海区域
    private final int FLAG_NOTCH_LANDSCAPE = 0x00000400;

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public boolean hasNotchInScreen(Window window) {
        try {
            return "1" == SystemProperties.get("ro.miui.notch");
        } catch (Exception e) {
            return false;
        }
    }

    //小米的状态栏高度会略高于刘海屏的高度，因此通过获取状态栏的高度来间接避开刘海屏,宽度未知，直接返回了屏幕宽度
    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public List<Rect> getNotchSize(Window window) {
        ArrayList<Rect> result = new ArrayList<>();

        Context context = window.getContext();
        Rect rect = new Rect();
        rect.top = 0;
        rect.bottom = getStatusBarHeight(context);
        rect.left = 0;
        rect.right = context.getResources().getDisplayMetrics().widthPixels;
        result.add(rect);

        return result;
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void setWindowLayoutAroundNotch(Window window) {
        int flag = FLAG_NOTCH_IMMERSIVE | FLAG_NOTCH_PORTRAIT | FLAG_NOTCH_LANDSCAPE;
        try {
            Method method = window.getClass().getMethod("addExtraFlags", int.class);
            method.invoke(window, flag);
        } catch (Exception e) {
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void setWindowLayoutBlockNotch(Window window) {
        int flag = FLAG_NOTCH_IMMERSIVE | FLAG_NOTCH_PORTRAIT | FLAG_NOTCH_LANDSCAPE;
        try {
            Method method = window.getClass().getMethod("clearExtraFlags", int.class);
            method.invoke(window, flag);
        } catch (Exception e) {
        }
    }

    private int getStatusBarHeight(Context context) {
        int result = 0;
        int resId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resId > 0) {
            result = context.getResources().getDimensionPixelSize(resId);
        }
        return result;
    }
}
